package com.lsongh.service;

import com.lsongh.model.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017/10/26.
 */
@Repository("jdbcStudentService")
public class StudentServiceImpl implements StudentService {

    private JdbcTemplate jdbcTemplate;

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    /**
     * 增加，删除，更新都使用update方法（第一个参数sql语句，第二个参数对应为形参）
     *
     */
    public void add(Student student) {
        this.jdbcTemplate.update(
                "INSERT into student (student_address,student_name,student_sex,student_phone) values (?,?,?,?)",
                student.getStudentAddress(), student.getStudentName(), student.getStudentSex(), student.getStudentPhone());
    }

    public void update(Student student) {
        this.jdbcTemplate.update(
                "update student set student_address = ?,student_name=?,student_sex=?,student_phone=?  where stuent_id = ?",
                student.getStudentAddress(), student.getStudentName(), student.getStudentSex(), student.getStudentPhone(), student.getStuentId());

    }

    public void delete(int studentId) {
        this.jdbcTemplate.update("delete from student where stuent_id = ?", studentId);
    }

    /**
     * 查询单个学生信息用queryForObject
     * 第二个参数为返回的是一个什么类型，如String,int,或者自定义的student对象
     */
    public Student load(int studentId) {
        String sql = "select  * from student where stuent_id = ? ";
        return this.jdbcTemplate.queryForObject(sql, new StudentRowMapper(), studentId);
    }

    public List<Student> list() {
        String sql="select * from student";
        return this.jdbcTemplate.query(sql,new StudentRowMapper());

    }

    /**
     * 内部类，返回一个student对象，query方法的第二个参数
     */
    class StudentRowMapper implements RowMapper<Student> {
        //rs为返回结果集，以每行为单位封装着
        @Override
        public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            Student student = new Student(
                    rs.getString("student_address"),
                    rs.getString("student_name"),
                    rs.getString("student_sex"),
                    rs.getString("student_phone")
            );
            student.setStuentId(rs.getInt("stuent_id"));
            return student;
        }
    }
}
